﻿/*  ----------------------------------------------------------------------------
 *  DES-Release 2
 *  ----------------------------------------------------------------------------
 *  File:       WorkerBase.cs
 *  Author:     nitinkoshy@gmail.com
 *  Source:     http://des.codeplex.com/
 *  ----------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Configuration;
using System.Diagnostics;

namespace DES.Server.Service.Workers
{
    public abstract class WorkerBase : IServerWorker
    {
        private Thread _visitorThread;
        private bool _stopped = false;
        private int _threadSleepTime;


        public void CheckQueue(object data)
        {

            DESServerService serverService = (DESServerService) data;
            while (!_stopped)
            {
                Thread.Sleep(_threadSleepTime);
                PerformTask(serverService);
            }
        }

        #region IServerWorker Members

        public abstract void PerformTask(DESServerService serverService);
        public abstract string GetWorkerName();
        public abstract int GetThreadSleepTime();

        public void StartMonitoring(DESServerService serverService)
        {
            _threadSleepTime = GetThreadSleepTime();
            _visitorThread = new Thread(CheckQueue);
            _visitorThread.Start(serverService);

            Trace.Write(String.Format("[{0}/{1}]:", serverService.ServerInfo.Id, DateTime.Now.ToShortTimeString()));
            Trace.WriteLine(String.Format("{0} thread started with sleep time {1}", GetWorkerName(), _threadSleepTime.ToString()));
        }

        public void StopMonitoring()
        {
            _stopped = true;

        }

        #endregion
    }
}
